/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-09-01 10:01:30
 * @LastEditors: 商晓彬
 * @LastEditTime: 2022-01-04 14:39:26
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TreeNode } from 'primeng/api';
import { CreateOrEditBopTreeModalComponent } from '@app/admin/bop/create-or-edit-boptree-modal.component';
import { OrganizationUnitsTreeComponent } from '@app/admin/shared/organization-unit-tree.component';
import {
    ProductionDesignServiceProxy, CommonServiceProxy, PartsDeliveryServiceProxy,
    PartsOutboundInput, MatchingStoreInput, WorkMatching
} from '@shared/service-proxies/service-proxies';
import { Paginator } from 'primeng/components/paginator/paginator';
import * as moment from 'moment';
import { BackWarehouseComponent } from '../back-warehouse/back-warehouse.component';
import { MessageService } from '@abp/message/message.service';
@Component({
    selector: 'app-mating-ex-warehouse',
    templateUrl: './mating-ex-warehouse.component.html',
    styleUrls: ['./mating-ex-warehouse.component.less']
})
export class MatingExWarehouseComponent extends AppComponentBase {
    @ViewChild('BackWarehouseComponent') BackWarehouseComponent: BackWarehouseComponent;
    //父组件传参
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('createOrEditBopTreeModal') createOrEditBopTreeModal: CreateOrEditBopTreeModalComponent;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() warehouseInfo: any;//仓库信息
    @Input() checktype: any
    active = false;
    files2: any = [];//树数据
    files1: any;//树表格数据
    selectedFiles: any;//选择的树
    saving = false;
    loading: boolean;
    loadingtree: boolean;
    module = undefined;
    moduleOptions = [];
    sendTime = undefined;
    sendTimeOptions = [];
    selectedTreeTable: any = [];//树表格选择
    selectRow: any;// 表格选择
    rowData = {};
    chooseFlag = undefined;//0 配套新增查看 1 配套新增选择 2配套修改查看 3 配套修改选择  4配套退库查看  5配套 退库选择 6配套退库记录查看
    title = undefined;
    stepFlag = false;
    oldTable = [];
    chooseSon = [];
    saveInput = [];
    arr4: any[] = [];
    saveFlag = true;
    constructor(
        injector: Injector,
        private _productionDesignServiceProxy: ProductionDesignServiceProxy,
        private _commonServiceProxy: CommonServiceProxy,
        private _partsDeliveryServiceProxy: PartsDeliveryServiceProxy,
        private _messageService: MessageService,
    ) {
        super(injector);
    }
    ngOnInit() { }
    onNodeUnselect(data) {
        for (let i = 0; i < this.saveInput.length; i++) {
            let item = this.saveInput[i];
            if (item.loadDetailsId === data.node.data.loadDetailsId) {
                this.saveInput.splice(i, 1);
            }
        }
    }
    backToEx(data) {
        setTimeout(() => {
            if (data.parent != null) {
                let flag = false;
                for (const item of this.selectedTreeTable) {
                    if (item.data.id == data.parent.node.data.id) {
                        flag = true;
                    }
                }
                if (!flag) {
                    this.selectedTreeTable.push(data.parent.node);
                }
                // 匹对如果该工步已选择物料，要把之前的给覆盖而不是Push
                if (this.saveInput.length != 0) {
                    for (let i = 0; i < this.saveInput.length; i++) {
                        let item = this.saveInput[i];
                        if (item.loadDetailsId == data.choose.loadDetailsId) {
                            this.saveInput[i] = data.choose
                        } else {
                            this.saveInput.push(data.choose);
                        }
                    }
                } else {
                    this.saveInput.push(data.choose);
                }
            }
            this.files1 = data.table;
        }, 5);
    }
    check(row) {
        this.chooseSon = [];
        if (this.selectedTreeTable.length != 0) {
            for (const item of this.saveInput) {
                if (item.loadDetailsId == row.node.data.loadDetailsId) {
                    this.chooseSon = item.storeIdList;
                }
            }
        }
        this.rowData = row;
        this.chooseFlag = 1;
        this.title = '选择出库';
        this.oldTable = this.files1;
        this.files1 = [];
        //选择出库
        setTimeout(() => {
            this.BackWarehouseComponent.show();
        }, 5);
    }
    watch(row) {
        //查看
        this.rowData = row;
        this.chooseFlag = 0;
        this.oldTable = this.files1;
        this.files1 = [];
        this.title = '出库查看';
        setTimeout(() => {
            this.BackWarehouseComponent.show();
        }, 5);
    }
    save() {
        let input = new MatchingStoreInput();
        input.nodeId = this.selectedFiles.id;
        input.matchings = [];
        for (let i = 0; i < this.selectedTreeTable.length; i++) {
            let item = this.selectedTreeTable[i];
            if (item.data.nodeLevel == 9) {
                this.selectedTreeTable.splice(i, 1);
            }
        };
        let list2 = [];//配套过物料的工步 find
        let list3 = [];//没配套过物料的工步
        for (const parent of this.selectedTreeTable) {
            let same = this.saveInput.filter(item => item.loadDetailsId == parent.data.loadDetailsId);
            if (same.length > 0) {
                list2.push(same[0]);
            }
        }
        list3 = this.selectedTreeTable.filter(v => !list2.some((item) => item.loadDetailsId === v.data.loadDetailsId));
        input.matchings = list2;
        for (const item of list3) {
            let data = new WorkMatching();
            data.loadDetailsId = item.data.loadDetailsId;
            input.matchings.push(data);
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._partsDeliveryServiceProxy.matchingStore(input)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success('出库成功！');
                        this.modalSave.emit();
                        this.close();
                    } else {
                        this._messageService.error(result.message);
                    }

                });
        }
    }
    onChange(event) {
        this.sendTimeOptions = [{ label: 1, value: 1 }, { label: 2, value: 2 }];
    }
    nodeSelect(event) {
        //树节点点击事件
        abp.ui.setBusy(undefined, '', 1);
        this.selectedFiles = event.node;
        let input = new PartsOutboundInput();
        input.nodeId = event.node.id;
        this._partsDeliveryServiceProxy.displayNodeDetails(input)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                abp.ui.clearBusy();
                if (event.node.nodeLevel == 8 || event.node.nodeLevel == 9) {
                    this.stepFlag = true;
                } else {
                    this.stepFlag = false;
                }
                this.files1 = result;
                this.expendAllForTable();
            });
        if (event.node.isRelation == 1) {
            this._productionDesignServiceProxy.getProductionTechquine(event.node.id)
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    result.forEach((node) => {
                        this.children(node);
                    });
                    let rowInfo = this.getTreeRecursion(this.files2, this.selectedFiles.id);
                    rowInfo.children = result;
                });
        }
    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current);
            }
        }
        return result;
    }
    //获取树结构
    getTreeInfo(): void {
        this.loadingtree = true;
        this._productionDesignServiceProxy.getProductionDesigenTree(this.module, this.sendTime)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.files2 = [];
                this.files2.push(result);
                if (Object.keys(result).length != 0) {
                    this.expandAll();
                }
                this.loadingtree = false;
            });
    }
    private children(node) {
        if (node.treeList) {
            node.children = node.treeList;
            node.children.forEach((childNode) => {
                this.children(childNode);
            });
        }
    }
    expendAllForTable() {
        for (const node of this.files1) {
            this.TreeExpandRecursive(node, true);
        }
    }
    expandAll() {
        this.files2[0].children = this.files2[0].treeList;
        this.files2[0].expanded = true;
        this.files2[0].children.forEach((node) => {
            this.children(node);
            this.expandRecursive(node, true);
        });
    }
    private TreeExpandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.TreeExpandRecursive(childNode, isExpand);
            });
        }
    }
    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    show(): void {
        this.active = true;
        this.modal.show();
    }
    close(): void {
        this.active = false;
        this.files2 = [];
        this.files1 = [];
        this.module = undefined;
        this.sendTime = undefined;
        this.selectedFiles = undefined;
        this.selectedTreeTable = [];
        this.modal.hide();
    }
    //打开弹窗
    onShown(): void {
        //型号
        this._commonServiceProxy.getModelList(
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.moduleOptions = [];
                this.moduleOptions = result;
            });
    }
    getLotNo(event) {
        //发次
        this._commonServiceProxy.getLotNoList(
            this.module
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.sendTimeOptions = [];
                this.sendTimeOptions = result;
            });
    }
}
